package com.antler.smt.admin.shiro;


import com.antler.smt.entity.UserEntity;
import com.antler.smt.response.admin.ListPermissionResp;
import com.antler.smt.service.admin.PermissionService;
import com.antler.smt.service.admin.UserService;
import com.antler.smt.utils.StringUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;


/**
 * 认证
 *
 * @author vic
 * @date 2018-03-26 19:43
 */
@Component
public class UserRealm extends AuthorizingRealm {

    /**
     * 用户信息Mapper
     */
    @Autowired
    private UserService userService;
    /**
     * 权限信息Mapper
     */
    @Autowired
    private PermissionService permissionService;

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        UserEntity user = (UserEntity) principals.getPrimaryPrincipal();
        Long userId = user.getId();

        List<String> permsList = null;

        //系统管理员，拥有最高权限
        if (userId == 1) {
            List<ListPermissionResp> menuList = permissionService.listPerms();
            permsList = new ArrayList<>(menuList.size());
            for (ListPermissionResp menu : menuList) {
                permsList.add(menu.getPerms());
            }
        } else {
            permsList = userService.queryAllPerms(userId);
        }

        //用户权限列表
        Set<String> permsSet = new HashSet<String>();
        for (String perms : permsList) {
            if (StringUtil.isEmpty(perms)) {
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String jobNum = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());

        //查询用户信息
        UserEntity user = userService.queryByJobNum(jobNum);

        //账号不存在
        if (user == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }

        //密码错误
        if (!password.equals(user.getPassword())) {
            throw new IncorrectCredentialsException("账号或密码不正确");
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
        return info;
    }
}
